package com.zzptc.sky.bdsjws.utils;

import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;

import com.zzptc.sky.bdsjws.MyApplication;
import com.zzptc.sky.bdsjws.R;
import com.zzptc.sky.bdsjws.db.MobileInfoDao;
import com.zzptc.sky.bdsjws.vo.Contacts;
import com.zzptc.sky.bdsjws.vo.MobileInfo;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/4/23.
 */

public class MyUtil {
    public static SharedPreferences getSharedPre() {
        return MyApplication.getContext().getSharedPreferences("loginnew", Context.MODE_PRIVATE);
    }

    //判断SD卡是否存在
    public static boolean isSD() {
        boolean flag = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (flag) {
            return true;
        }
        return false;
    }

    //得到储存路径
    public static File getDirs() {
        if (isSD()) {
            return Environment.getExternalStorageDirectory();
        }
        //return Environment.getDownloadCacheDirectory();
        return Environment.getExternalStorageDirectory();
    }

    public static Intent getInstall(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        return intent;
    }

    //求日期差
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    public static int getVersionCode(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    //复制文件到手机
    public static void copyFileToMobile(Context context, String fromdbname, String todbname) throws Exception {
        URL url = context.getClass().getClassLoader().getResource("assets/" + fromdbname);
        //文件路径
        String dbfile = "/data/data/" + MyApplication.getContext().getPackageName() + "/data3333";
        File fileMobiledir = new File(dbfile);
        if (!fileMobiledir.exists()) {
            fileMobiledir.mkdirs();
        }
        File dbfilemobiles = new File(fileMobiledir + "/" + todbname);
        if (!dbfilemobiles.exists()) {
            dbfilemobiles.createNewFile();
        }
        FileUtils.copyURLToFile(url, dbfilemobiles);
        //第一个参数  是包含路径源文件   第二个参数  目的地包含路径的文件
    }

    /**
     * 得到手机上的联系人 信息
     * 姓名  电话号码  手机归属地   三个属性封装成一个实体类 vo pojo entity
     *
     * @return
     */

    public static List<Contacts> getAllContacts() {

        List<Contacts> lists = new ArrayList<Contacts>();

        //通过内容提供查询联系人
        //访问联系人的uri
        //ContactsContract.Contacts.CONTENT_URI
        //访问电话号码的 uri
        //ContactsContract.CommonDataKinds.Phone.CONTENT_URI

        ContentResolver contentPesolver = MyApplication.getContext().getContentResolver();
        //   Uri uri= ContactsContract.Contacts.CONTENT_URI;

        Cursor cursor = contentPesolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));//手机联系人
                int num = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String phonenum = null;
                //如果大于0，表示有电话号码
                if (num > 0) {
                    phonenum = getPhonenuByID(id);
                }
                //获取手机归属地？？？
                //准备工作  将外部数据拷贝到手机中的方法 1.在哪里拷贝方法MyAppication
                String addr = null;
                addr = getAddyessByTel(phonenum);


                Contacts contacts = new Contacts(id, name, phonenum, addr);
                lists.add(contacts);
            }
            cursor.close();
        }
        return lists;
        /*if (cursor==null){

        }else {
            while (cursor.moveToNext()){
                Contacts  contacts1=new Contacts();
                //获取id
                int id=cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            //获取联系人的姓名
                String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                //手机号码   关联到DATA表
                //手机归属地  涉及外部数据库
            }
        }*/


    }

    //正式表达式
    public static String getAddyessByTel(String tel) {
        String address = null;
        //MobileInfo mobileInfo=null;
        //  String[] aa=tel.split(" ");
        String newtel = tel.replace("", "").replace("-", "");
        String telnum = null;
        if (newtel.length() == 11 && newtel.matches("^1[34578]\\d{9}$")) {
            //手机号码
            telnum = newtel.substring(0, 7);
            address = getMobileAddrByTel(telnum);

        } else {
            //座机号码
            int length = newtel.length();

            //座机号码？   3位区号+七位号码/3位区号+八位号码/4位取号+八位号码
            switch (length) {
                case 10:
                    getZUOAddrByTel(newtel, 3);
                    break;
                case 11:
                    //分两种情况  3+8  4+7
                      address=getZUOAddrByTel(newtel,3);
                    if(address==null){
                        address=getZUOAddrByTel(newtel,4);

                    }
                    break;
                case 12:
                    address=getZUOAddrByTel(newtel,4);
                    break;
                default:
                    address="未知";
            }
        }
        return address;
    }

    public static String getZUOAddrByTel(String tel, int length) {
        MobileInfo mobileInfo = MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.AreaCode.eq(tel.substring(0, length))).limit(1).distinct().unique();
        return mobileInfo.getMobileArea();
    }

    public static String getMobileAddrByTel(String tel) {
        MobileInfo mobileInfo = MyApplication.getMobiledaoSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(tel)).distinct().unique();
      return   mobileInfo.getMobileArea();
    }
    public  static  String getPhonenuByID(int id){
        String telnum=null;
        ContentResolver contentPesolver=MyApplication.getContext().getContentResolver();
        Cursor cursor=contentPesolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?",new String[]{id+""},null);
     if (cursor!=null){
         if (cursor.moveToNext()){
             //我这只取一个电话号码
             telnum=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
         }

     }
        cursor.close();
        return telnum;
    }
//    public void test() throws IOException {
//        File file=new File("c:/ccc/c");
//        if(!file.exists()){
//            file.mkdir();
//        }
//        File dbfile=new File("c:/cc/c/1.txt");
//        if(!dbfile.exists()){
//            dbfile.createNewFile();
//        }
//    }  mkdir是创建文件夹
}
